const storageService = require('./storage')

/**
 * 
 * @param {string} id 
 * @returns {boolean} 是否存在已启用的task
 */
function disablePlayerTimerTasks(id) {
  const playerModeData = storageService.getPlayerModeData(id)
  const playerTimerTasks = playerModeData?.timerTasks || []
  let flag = false
  playerTimerTasks.forEach(task => {
    if (task.enabled) {
      task.enabled = false
      flag = true
    }
  })
  if (flag) {
    storageService.savePlayerModeData(id, {
      timerTasks: playerTimerTasks
    })
  }
  return flag
}

/**
 * 获取模式名称
 * @param {string} id 
 * @returns  {array} 模式名称
 */
function getModeNames(id) {
  const newPresets = getPresets(id)
  return newPresets.map(mode => mode.name)
}

/**
 * 获取模式名称
 * @param {string} id 
 * @returns  {array} 模式名称
 */
function getModeOptions(id) {
  const newPresets = getPresets(id)
  const modeOptions = []
  newPresets.forEach(preset => {
    modeOptions.push({
      name: preset.name,
      modeCode: `p${preset.id}`,
      modeType: 'player_mode'
    })
  })
  return modeOptions
}

/**
 * 初始化预设数据
 * @param {string} id 
 * @param {array} storagePresets 
 * @returns  {array} presets数据
 */
function initializePresets(id, storagePresets) {
  // 如果没有存储的预设数据，返回默认预设
  if (!storagePresets || !Array.isArray(storagePresets) || storagePresets.length === 0) {
    console.log('未找到存储的预设数据，使用默认预设');
    let channels = storageService.getDeviceChannels(id)
    let presets = []
    for (var i = 0; i < 15; i++) {
      let obj = {
        id: (i + 1),
        name: '自定义' + (i + 1),
        selected: i == 0
      }
      let newChannels = JSON.parse(JSON.stringify(channels))
      newChannels.forEach(ele => {
        ele.v = 0
      })
      obj.channels = newChannels
      presets.push(obj)
    }
    return presets
  } else {
    return storagePresets
  }
}

function getPresets(id){
  const presets = storageService.getPlayerModePresets(id)
  return initializePresets(id, presets)
}

/**
 * 获取玩家模式灯光值
 * @param {string} id 
 * @param {number} index 
 * @param {number} brightness 
 */
function getValsByIdx(id,index,brightness){
  const presets = storageService.getPlayerModePresets(id)
  const vals=[]
  presets[index].channels.forEach(ele=>{
    vals.push(parseInt(ele.v*brightness/100))
  })
  return vals
}

module.exports = {
  disablePlayerTimerTasks,
  getModeNames,
  //getModeOptions,
  initializePresets,
  getValsByIdx,
  getPresets,
}